package com.gisuni.sddc.service;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import com.gisuni.sddc.dao.UserInfoDao;
import com.gisuni.sddc.model.Response;
import com.gisuni.sddc.model.Userinfo;
import com.gisuni.sddc.platformManager.dao.LogDao;
import com.gisuni.sddc.platformManager.model.Organization;
import com.gisuni.sddc.platformManager.model.UserOrganization;
import com.gisuni.sddc.util.CookieUtil;
import com.gisuni.sddc.util.MD5Util;
import com.gisuni.sddc.util.StringUtil;

@IocBean
public class LoginService {

//	private Log log = Logs.getLog(LoginService.class);
	private  Log log = Logs.getLog(LoginService.class);
	@Inject
	private UserInfoDao   userInfoDao;
	
	@Inject
	private LogDao   logDao;

	/**
	 * 查询数据
	 * 
	 * @param 
	 * @return
	 */
	public Response queryLoginUser(HttpServletRequest request,Response res, HttpServletResponse rep) {
		request.getSession().invalidate();//由于多处用了Session
		Response response = new Response();
		response.setSuccess(false);
		String Result=null;
		StringBuffer selectstr=null;
		String andSelect = "";
		try {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			String loginCheckbox = request.getParameter("loginCheckbox");// 1:记住用户名

			if(StringUtil.isNullOrEmpty(username)||StringUtil.isNullOrEmpty(password)){ //为空时校验
				return response;
			}
			
			String userId ="";
			log.debug("用户:"+username+" 正在登录....;时间:"+new Date());
			//诚信所验证方式
//			userId = checkUser(username,password);
			
//			本系统验证MD5验证
			userId = checkingUser(username,password);
			log.debug("用户:"+username+" 登录成功....;时间:"+new Date());
			//保存日志信息
			com.gisuni.sddc.platformManager.model.Log logs  = new com.gisuni.sddc.platformManager.model.Log();
			logs.setUserName(username);
			logs.setUserId(userId);
			logs.setType("1");
			logs.setStatus("2");
	   		 
			 String logId = UUID.randomUUID().toString().replaceAll("-", "");
	   		 logs.setId(logId);
	   		 logs.setCreateTime(new Date());
   		 
			if(StringUtil.isNullOrEmpty(userId)){ //抓取登录信息失败
				response.setResult("wrongIn");
				logs.setInfo("抓取登录信息失败");
				logDao.addLog(logs);
				return response;
			}else if("0".equals(userId)){
				logs.setInfo("账户密码错误");
				logDao.addLog(logs);
				return response;
			}
			
			logs.setInfo("登录成功");
			logs.setStatus("1");
			logDao.addLog(logs);
			
			
		  
			//获取角色可支配的资源 读取城信所系统的
			/**
			 select t4.userid,t4.username,t4.displayname, listagg( t4.rolename, ',' ) within group ( order by t4.rolename ) as rolename from (
			  select t3.userid,t3.username,t3.displayname, t1.roleid，t1.rolename from (select t.userid,t.username,t.displayname, t2.roleid 
			  from sddconemap.userinfo t ,sddconemap.user_role t2 where t.userid = t2.userid) t3,sddconemap.roleinfo t1 where t3.roleid=t1.roleid
			  ) t4 group by t4.userid,t4.username,t4.displayname
			 */
			StringBuffer sbf = new StringBuffer();
			sbf.append(" select t4.userid,t4.username,t4.displayname, listagg( t4.rolename, ',' ) within group ( order by t4.rolename ) as rolename from (");
			sbf.append(" select t3.userid,t3.username,t3.displayname, t1.roleid，t1.rolename from (select t.userid,t.username,t.displayname, t2.roleid ");
            sbf.append(" from sddconemap.userinfo t ,sddconemap.user_role t2 where t.userid = t2.userid) t3,sddconemap.roleinfo t1 where t3.roleid=t1.roleid ");
            sbf.append(" and t3.userid =  "+userId );
            sbf.append(" ) t4 group by t4.userid,t4.username,t4.displayname ");
            
            //读取本系统的  前端根据userType来区分管理员
            StringBuffer sbf1 = new StringBuffer();
            sbf1.append(" select t.user_id userid,t.user_name username,t.user_type userType,t.displayname,t2.role_area ,t2.role_area_type,t3.ORGANIZATION_COMPANY_ID,");
            sbf1.append("t3.ORGANIZATION_BUSINESS_ID,t3.ORGANIZATION_DEVELOP_ID,t3.companyName,t3.busiName,t3.devName  from sddcgisplatform.user_info t,");
            sbf1.append(" sddcgisplatform.user_r_role t1,sddcgisplatform.role_info t2, sddcgisplatform.v_user_organization_detail t3 where t.user_id = t1.user_id and t.user_id = t3.USER_ID and t1.role_id=t2.role_id ");
            sbf1.append(" and t.user_id='"+userId+"'");            
//            select t4.user_id,t4.user_name,t4.displayname, listagg( t4.role_name, ',' ) within group ( order by t4.role_name ) as rolename from ( 
//            		  select t3.user_id,t3.user_name,t3.displayname, t1.role_id，t1.role_name from (select t.user_id,t.user_name,t.displayname, t2.role_id  
//            		  from sddcgisplatform.user_info t ,sddcgisplatform.user_r_role t2 where t.user_id = t2.user_id) t3,sddcgisplatform.role_info t1 where t3.role_id=t1.role_id  
//            		  and t3.user_id =  '74' 
//            		  ) t4 group by t4.user_id,t4.user_name,t4.displayname 
            
			
            //TODO 正式环境时需用上面SQL , 当不能使用listagg函数时
//           if("gh".equals(username)){
//        	   sbf = new StringBuffer("select * from sddconemap.user_privilege t  where t.userid =  "+userId );
//           }
            
            
            String  result = userInfoDao.executeSQL(sbf1.toString());//数据库版
//			String result = "[{\"DISPLAYNAME\":\"管理员\",\"ROLENAME\":\"管理员\",\"USERNAME\":\"gh\",\"USERID\":\"74\"}]";//不用数据库版版
			Userinfo user = new Userinfo();
			user.setUsername(username);
			user.setPassword(password);
			//保存Cookie
			if("1".equals(loginCheckbox) || "true".equals(loginCheckbox) ){
				CookieUtil.saveCookie(user, rep);
			}else{// 清除cookie
				CookieUtil.clearCookie(rep);
			}
			
			request.getSession().setAttribute("userInfo", result);
			
			//可管理/查看的人员
			getManageredUser(request,userId);
			//可视区域
			setRoleArea(result,request);
			//可查看的模块
			setRoleModule(request,userId);
			//可查看的资源树
			setRoleResource(request,userId);
			
//			System.out.println(areaResult.toString());
			
//          判断是否为集团负责人[聚合模块:项目状态中只有集团负责人才可使用该模块,可查看其集团下的数据] 现在全部人可查看
//			String isCompanyLeader =  "select   case   t1.organization_name   when '广州南' then '广州市'   when '白云组' then '广州市'    when '广州北' then '广州市' " 
//               +" when '花都组' then '广州市' else substr(t1.organization_name,0,length(t1.organization_name)-2)||'市' end  company_name "
//               +" from sddcgisplatform.organization t1 where  t1.ORGANIZATION_MANAGER_ID='"+userId+"' and t1.organization_type='1' ";
//			
//			String  data = userInfoDao.queryUserPrivilege(isCompanyLeader);
//			String companyName =  jsonToString(data,"COMPANY_NAME");
//			if(!StringUtil.isNullOrEmpty(companyName)){
//				//不可能出现一个人同时是两个集团的负责人
//				request.getSession().setAttribute("companyName", companyName.split(",")[0]);
//			}    		
	
			response.setResult("success");
			response.setSuccess(true);
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.toString()+"登录有问题了");
			return response;
		}
	}
	
	//读取角色-资源树
	private void setRoleResource(HttpServletRequest request, String userid) {
		/**
		 * 
		 * 1.图层表-服务表关联 得到服务图层信息 
		 * 2.服务图层信息关联resource_r_layer 得到所有图层+resource信息
		 * 3.resource_info 关联2的结果 :详细专题信息+图层相关
		 * 4.role_r_resource 角色过滤3的结果
		 * 
	  select rlyrs.* from SDDCGISPLATFORM.role_r_resource t left join (
	    select t.id resource_id,t.resource_name,t.resource_index,t.parent_id resource_parent_id,rlys.* from SDDCGISPLATFORM.resource_info t 
	    left join (select lys.*,rly.resource_id layer_resource_id,rly.fields from ( select ly.id layer_id,ly.layer_name,ly.table_name,ly.layer_index,ly.server_id,si.server_name,si.dynamics_url,si.feature_url from SDDCGISPLATFORM.layer_info ly 
	    left join SDDCGISPLATFORM.server_info si on ly.server_id = si.id where si.status='1') lys 
	    left join SDDCGISPLATFORM.resource_r_layer rly on rly.layer_id=lys.layer_id  ) rlys on t.id = rlys.layer_resource_id
	  ) rlyrs on t.resource_id = rlyrs.resource_id where t.role_id in ( select role_id from SDDCGISPLATFORM.user_r_role where user_id = '123' )
		 */
		
		StringBuffer sbf = new StringBuffer();
		sbf.append("select rlyrs.* from SDDCGISPLATFORM.role_r_resource t left join ( ");
		sbf.append(" select t.id resource_id,t.resource_name,t.resource_index,t.parent_id resource_parent_id,rlys.* from SDDCGISPLATFORM.resource_info t  ");
		sbf.append(" left join (select lys.*,rly.resource_id layer_resource_id,rly.fields,rly.edittable,rly.changelevel,rly.tileflag from ( select ly.id layer_id,ly.layer_name,ly.table_name,ly.layer_index,ly.server_id,si.server_name,si.dynamics_url,si.feature_url from SDDCGISPLATFORM.layer_info ly  ");
		sbf.append(" left join SDDCGISPLATFORM.server_info si on ly.server_id = si.id where si.status='1') lys  ");
		sbf.append(" left join SDDCGISPLATFORM.resource_r_layer rly on rly.layer_id=lys.layer_id  ) rlys on t.id = rlys.layer_resource_id ");
		sbf.append(") rlyrs on t.resource_id = rlyrs.resource_id ");
		sbf.append(" where t.role_id in ( select role_id from SDDCGISPLATFORM.user_r_role where user_id = '"+userid+"' ) ");
		System.out.println("=="+sbf.toString());
		String result = userInfoDao.executeSQL(sbf.toString());
		if("[]".equals(result)){
			request.getSession().setAttribute("roleResources", "");
		}else{
			result = result.replaceAll("'", "%");
			request.getSession().setAttribute("roleResources", result);
		}
		
	}

	//读取角色-模块
	private void setRoleModule(HttpServletRequest request, String userid) {
		 
 /**
  *        1.图层表-服务表关联 得到服务图层信息 
		 * 2.服务图层信息关联module_r_layer 得到所有图层+module信息
		 * 3.module_info 关联2的结果::详细模块信息+图层相关
		 * 4.role_r_module 角色过滤3的结果
 select rlyrs.* from SDDCGISPLATFORM.role_r_module t left join (   select t.id module_id,t.model_name,t.model_index,t.parent_id morule_parent_id,rlys.* from SDDCGISPLATFORM.module_info t    left join (    select lys.*,rly.module_id layer_module_id,rly.fields,rly.layerparam from (select ly.id layer_id,ly.layer_name,ly.layer_index,ly.server_id,ly.table_name,si.server_name,si.dynamics_url,si.feature_url from SDDCGISPLATFORM.layer_info ly   left join SDDCGISPLATFORM.server_info si on ly.server_id = si.id where si.status='1') lys   left join SDDCGISPLATFORM.module_r_layer rly  on lys.layer_id = rly.layer_id ) rlys on t.id = rlys.layer_module_id ) rlyrs on t.module_id = rlyrs.module_id   where t.role_id in ( select role_id from SDDCGISPLATFORM.user_r_role where user_id = '74' )
  * 
  */
		StringBuffer sbf = new StringBuffer();
		sbf.append("select rlyrs.* from SDDCGISPLATFORM.role_r_module t left join ( ");
		sbf.append("  select t.id module_id,t.model_name,t.model_index,t.parent_id morule_parent_id,rlys.* from SDDCGISPLATFORM.module_info t  ");
		sbf.append("  left join (    select lys.*,rly.module_id layer_module_id,rly.fields,rly.layerparam from (select ly.id layer_id,ly.layer_name,ly.layer_index,ly.server_id,ly.table_name,si.server_name,si.dynamics_url,si.feature_url from SDDCGISPLATFORM.layer_info ly  ");
	    sbf.append(" left join SDDCGISPLATFORM.server_info si on ly.server_id = si.id where si.status='1') lys  ");
	    sbf.append(" left join SDDCGISPLATFORM.module_r_layer rly  on lys.layer_id = rly.layer_id ) rlys on t.id = rlys.layer_module_id ");
		sbf.append(") rlyrs on t.module_id = rlyrs.module_id  ");
		 
		sbf.append(" where t.role_id in ( select role_id from SDDCGISPLATFORM.user_r_role where user_id = '"+userid+"' )");
	 
		System.out.println("=="+sbf.toString());
		String result = userInfoDao.executeSQL(sbf.toString());
		if("[]".equals(result)){
			request.getSession().setAttribute("roleModules", "");
		}else{
			
			result = result.replaceAll("'", "%");
			request.getSession().setAttribute("roleModules", result);
		}
		
	
	}

	//登录验证
	private String checkingUser(String username, String password) throws Exception{
		String pwd = MD5Util.str2MD5(password);
		String userId  = userInfoDao.queryUserId(username,pwd);
		if(userId == null ){
			userId="0";
		}
		return userId;
	}


	
	/**
	 * 用户可管理的人员[根据部门]
	 * @param request
	 * @param userId
	 */
	public void getManageredUser(HttpServletRequest request,String userId){
		/** 这里的BUG是一个人必须属于一个组织,如果只是负责人而没有组织会查不到数据[新增人员时组织时必填项]
		          逻辑: 通过[用户组织表] 关联 [组织表] 得到所有用户所在的组织关系及其作为负责人所在的部门
	                                     若不是负责人则只需查所在的组织得到该组织所有所在的人员
	                                     若是负责人则查询到其所有子部门,再通过子部门得到对应的人员
		 */
		List<String> orgIdList = new ArrayList<String>(); //最终可查看部门
		List<String> orgMenagerIdList = new ArrayList<String>();//管理的所在部门 (一个人可能是多个部门的负责人)
		
		//查询所有人所在组织+可管理的组织 (一对多)
		/*
		select t.user_id,t.organization_company_id,t.organization_business_id,t.organization_develop_id,t1.user_name,t2.id managerOrgId,
 		t2.organization_type managerOrgType from sddcgisplatform.user_organization t left join sddcgisplatform.user_info t1 on t1.user_id = t.user_id left join sddcgisplatform.organization t2 on t.user_id = t2.organization_manager_id
		 * 
		 * */
		String findManagerDepartment = "select t.user_id,t.organization_company_id,t.organization_business_id,t.organization_develop_id,t1.user_name,t2.id managerOrgId,"
										+"t2.organization_type managerOrgType from sddcgisplatform.user_organization t left join sddcgisplatform.user_info t1 on t1.user_id = t.user_id left join sddcgisplatform.organization t2 on t.user_id = t2.organization_manager_id";
		
		List<UserOrganization> userOrg = userInfoDao.queryUserManagerOrg(findManagerDepartment);
		if(userOrg!=null && userOrg.size()>0){
			for(UserOrganization org : userOrg){
				if(userId.equals(org.getUserId())){//
					if(!StringUtil.isNullOrEmpty(org.getManagerOrganizationId())){ //不为空即是部门负责人
						if("3".equals(org.getManagerOrganizationType())){ // 类型为3时即拓展部负责人,查看的只是改拓展部
							orgIdList.add(org.getOrganizationDevelopId()+"::3");
						}else{  //事业部或集团负责人
							orgMenagerIdList.add(org.getManagerOrganizationId());
						}
					}else{ 
		                //   拓展组-->事业部-->集团
			        	if(!StringUtil.isNullOrEmpty(org.getOrganizationDevelopId() )){
			        		orgIdList.add(org.getOrganizationDevelopId()+"::3");
			        	}else if(!StringUtil.isNullOrEmpty(org.getOrganizationBusinessId())){
			        		orgIdList.add(org.getOrganizationBusinessId()+"::2");
			        	}else if(!StringUtil.isNullOrEmpty(org.getOrganizationCompanyId())){
			        		orgIdList.add(org.getOrganizationCompanyId()+"::1");
			        	} 
					}
				}
			}
		}
		
		//查询可管理的所有子部门
		if(orgMenagerIdList!=null && orgMenagerIdList.size()>0){
			String menagerOrgId = orgMenagerIdList.get(0);
			StringBuffer sbf = new StringBuffer("select t.id,t.organization_type from SDDCGISPLATFORM.ORGANIZATION T start with T.ID = '"+menagerOrgId+"' connect by prior T.ID = T.parent_id ");
			 if(orgMenagerIdList.size()>1){
				for(int g=1;g<orgMenagerIdList.size();g++){
					 menagerOrgId = orgMenagerIdList.get(g);
					 sbf.append(" union select t.id,t.organization_type from SDDCGISPLATFORM.ORGANIZATION T start with T.ID = '"+menagerOrgId+"' connect by prior T.ID = T.parent_id ");
				}
			 }
			 List<Organization> res =  userInfoDao.queryAllMenagerOrg(sbf.toString());
			 
			 if(res!=null && res.size()>0){
				 for(Organization org : res){
					 if("3".equals(org.getOrganizationType())){
						 orgIdList.add(org.getId()+"::3");
					 }else if("2".equals(org.getOrganizationType())){
						 orgIdList.add(org.getId()+"::2");
					 }else if("1".equals(org.getOrganizationType())){
						 orgIdList.add(org.getId()+"::1");
					 }
				 }
			 }
		}
		
		StringBuffer userSbf = new StringBuffer();
		if(orgIdList!=null && orgIdList.size()>0){
			for(String id : orgIdList){
				String[] data = id.split("::");
				String orgId = data[0];
				String orgType = data[1];
				for(UserOrganization org : userOrg){ 
					
					    if("3".equals(orgType)){ //拓展
					    	
							if(orgId.equals(org.getOrganizationDevelopId())){
								userSbf.append(org.getUserName()+",");
							}
							
						}else if("2".equals(orgType)){ //事业部
							
							if(orgId.equals(org.getOrganizationBusinessId()) && StringUtil.isNullOrEmpty(org.getOrganizationDevelopId())){
								userSbf.append(org.getUserName()+",");
							}
							
						}else if("1".equals(orgType)){//集团
							
							if(orgId.equals(org.getOrganizationCompanyId()) && StringUtil.isNullOrEmpty(org.getOrganizationDevelopId()) && StringUtil.isNullOrEmpty(org.getOrganizationBusinessId())){
								userSbf.append(org.getUserName()+",");
							}
							
						}
				}
			}
		}
//		System.out.println(userSbf.toString());
		request.getSession().setAttribute("menagerUsers", userSbf.toString());
		
	}
	 
	/**
	 * 读取可视区域
	 */
	public void setRoleArea(String result , HttpServletRequest request ){
		String roleArea = null ; 
		boolean isDistinctType = true ; 
		StringBuffer roleAreaSbf  = new StringBuffer();
		
		JSONArray resultJsonArr = new JSONArray(result);
		if (resultJsonArr != null && resultJsonArr.length() > 0) {

			for (int i = 0; i < resultJsonArr.length(); i++) {
				JSONObject ret = (JSONObject) resultJsonArr.get(i);
				Iterator iterator = ret.keys();
				while (iterator.hasNext()) {
					String key = (String) iterator.next();
					
					//后台管理地址
					if("USERTYPE".equals(key)){
						String value = (String) ret.get(key);
						if("0".equals(value)){//管理员角色
							request.getSession().setAttribute("platformManagerUrl", "../client/backgroundManagement/views/index.jsp");
						} 
					}
					
					//可视区域
					if("ROLE_AREA".equals(key)){
						String value = (String) ret.get(key);
						roleArea = value;
						roleAreaSbf.append(value+":");
					}
					
					//可视区域类型
					if("ROLE_AREA_TYPE".equals(key)){
						String value = (String) ret.get(key);
						if("city".equals(value)){//城市
							isDistinctType = false;
						} 
						roleAreaSbf.append(value+"|");
					}
					
				}
			}
		}
		
		StringBuffer areaResult = new StringBuffer();
		
		String roleAreas = roleAreaSbf.toString();
		if(!"".equals(roleAreas)){
			String[] roleAreaData = roleAreas.split(":");
			for(String roleAreaStr : roleAreaData){
				String[] area = roleAreaStr.split("\\|");
				if(area.length==2){
				    roleArea = area[1];
					String areaType = area[0];
					if("city".equals(areaType)){ //当为城市类型时 查出具体行政区
						StringBuffer temp = new StringBuffer("'0'");
						String[] arr = roleArea.split(",");
						for(String t : arr){
							temp.append(",'"+t+"'");
						}
//						String findDistrict = " select name from sddcgisplatform.district where cityid in (select id from sddcgisplatform.city where name in ("+temp.toString()+"))";

						String findDistrict = " select district_name name from sddcgisplatform.city_distirict_townstreet where city_name in ("+temp.toString()+") group by district_name ";
						String  districtResult = userInfoDao.executeSQL(findDistrict);
//						request.getSession().setAttribute("roleArea", jsonToString(districtResult,"NAME"));
						

						
						//当市下面没有区数据时 ,就传市的名称到前端    TODO bug 当存在一个市下面有区数据,一个市下面没有数据市,该如何呢????? 
						String districtData = jsonToString(districtResult,"NAME");
//						if(StringUtil.isNullOrEmpty(districtData)){
//							districtResult = arr[0];
//						}else{
//							districtResult = districtData;
//						}
						
						areaResult.append(districtData+",");
						
						if(temp.toString().contains("中山市")){
							areaResult.append("中山市");
						}
						
					}else{
//						request.getSession().setAttribute("roleArea", roleArea);
						areaResult.append(roleArea+",");
//						System.out.println(roleArea);
					}

				}
				
			}
			
		}

		request.getSession().setAttribute("roleArea", areaResult.toString());
	}
	

	/**
	 * 调用诚心所登录的接口
	 * @param userName
	 * @param passWord
	 * 方式：http://10.1.10.230/SDDCOneMapServices/v1/cpzx/core/validate/verify/ 输入账号密码得到相应请求的链接，通过请求后抓取响应后的网页，匹配是否有登录成功的标示来判断是否登录成功;
	 * @return
	 */
	public String checkUser(String userName,String passWord){ // 回用户ID
	 
		String flag = "0";

            int maxLength=0;
		    StringBuffer buffer = new StringBuffer();  
	        System.setProperty("sun.net.client.defaultConnectTimeout", "5000");  
	        System.setProperty("sun.net.client.defaultReadTimeout", "5000");  
	        try {  
	        	
	    		userName = URLEncoder.encode(userName, "UTF-8"); // 当输入userName为中文时需处理下
	    		String key ="/"+userName+"/"+passWord;  
	    		String strUrl="http://10.1.10.230/SDDCOneMapServices/v1/cpzx/core/validate/verify/"+key;
	    		
	            URL newUrl = new URL(strUrl);  
	            
	            HttpURLConnection hConnect = (HttpURLConnection) newUrl  
	                    .openConnection();  
	            hConnect.setRequestMethod("GET");
	            // 读取内容  
	            BufferedReader rd = new BufferedReader(new InputStreamReader(  
	                    hConnect.getInputStream()));  
	            int ch;  
	            for (int length = 0; (ch = rd.read()) > -1  
	                    && (maxLength <= 0 || length < maxLength); length++)  
	                buffer.append((char) ch);  
	            String s = buffer.toString();  
	            // 返回的数据格式： "{\"status\":true,\"msg\":\"登录成功\",\"error\":\"\",\"userData\":{\"USERID\":\"74\",\"USERNAME\":\"gh\",\"PASSWORD\":\"Z2h8VG91ZmF6aG9uZ3hpbjY2OA==\",\"DISPLAYNAME\":\"管理员\",\"SHORTNAME\":\"\",\"USERTYPEID\":-2147483648,\"CREATETIME\":\"\",\"DESCRIPTION\":\"\",\"ISLOCKEDOUT\":-2147483648,\"EMAIL\":\"\",\"NICKNAME\":\"\",\"UPDATETIME\":\"\",\"WEIGHT\":-2147483648,\"USERIMAGES\":\"\/themes\/default\/images\/headimage\/gh.jpg\",\"SINDEX\":-2147483648,\"EXTRAID\":\"\"}}"
	            s=s.replaceAll("\\\\", "");
	            rd.close();  
	            hConnect.disconnect();  
	            if(s!=null&&!"".equals(s)){
	            	if(s.contains("\"status\":true")){//成功时 
	            	    int start = s.indexOf("USERID");
	            	    int end = s.indexOf("USERNAME");
	            		flag = s.substring(start+9, end-3);
	            		 
	            	}
	            } 
	        }catch (Exception e) {  
	        	log.error("抓取登录信息失败:"+e.getMessage());
	            return null;  
	        } 
	        return flag; 
	}


	public Response queryData(HttpServletRequest request, Response res, HttpServletResponse response) {
		try{
			String sql = request.getParameter("sql");
	        String  result = userInfoDao.executeSQL(sql); 
	        Response responseD = new Response();
			responseD.setResult(result);
			responseD.setSuccess(true);
			return responseD;
		} catch (Exception e) {
			log.error(e.getMessage());
			return null;
		}
	}
	
	public String jsonToString(String json ,String name){
		
		JSONArray resultJsonArr = new JSONArray(json);
		StringBuffer sbf = new StringBuffer();
		if (resultJsonArr != null && resultJsonArr.length() > 0) {
			for (int i = 0; i < resultJsonArr.length(); i++) {
				JSONObject ret = (JSONObject) resultJsonArr.get(i);
				Iterator iterator = ret.keys();
				while (iterator.hasNext()) {
					String key = (String) iterator.next();
					 
					if(name.equals(key)){
						String value = (String) ret.get(key);
						sbf.append(value+",");
					}
				}	
			}
		}
//		System.out.println(sbf.toString());
		return sbf.toString();
		
	}
	
}




